import React, { useState, useEffect } from 'react'
import { Button, Modal, Card, Cascader, Table, Pagination, message, Space, Tag, Form, Input } from 'antd'
import { EditOutlined, ExclamationCircleOutlined, DeleteOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'
import { getAllCate, addCateAPI, editCateAPI, delCateAPI } from '../../app/goodscate'
import './index.less'

const { confirm } = Modal
export default function Category () {
    // 添加分类的表单实例
    const [addCateForm] = Form.useForm()
    // 编辑分类的表单实例
    const [editCateForm] = Form.useForm()
    // 初始化查询分类
    const [queryInfo, setQueryInfo] = useState({type: 3, pagenum: 1, pagesize: 10})

    // 初始化商品分类
    const [cateList, setCateList] = useState([])

    // 商品分类级联菜单
    const [cascaderList, setCascaderList] = useState([])
    // 初始化商品分类总数
    const [cateTotal, setCateTotal] = useState(0)

    // 增加分类模态框显示
    const [isAddCateVisible, setIsAddCateVisible] = useState(false)

    // 编辑分类模态框显示
    const [isEditCateVisible, setIsEditCateVisible] = useState(false)

    // 分类选中的ID
    const [cateId, setCateId] = useState(0)

    // 按钮加载中....
    const [btnLoading, setBtnLoading] = useState(false)

    // 获取所有的商品分类
    const loadCateList = async () => {
        const { data, meta } = await getAllCate(queryInfo)
        if(meta.status !== 200) return message.error('获取分类列表数据失败')
        const { total, result } = data
        result.forEach((item, index) => item.index = index)
        setCateList(result)
        setCateTotal(total)
    }
    // 监测 queryInfo 改变发起查询商品分类的请求
    useEffect(() => {
        loadCateList()
    }, [queryInfo])

    // 添加分类
    const addCate = () => {
        setIsAddCateVisible(true)
        addCateForm.resetFields()
    }
    // 级联选着框聚焦
    const optionsFocus = () => {
        const cateObj = [...cateList]
        cateObj.forEach(item => {
            if(item.children?.length) {
                item.children.forEach(obj => {
                     if(obj.children?.length) {
                        obj.children = []
                     }
                })
            }
        })
        setCascaderList(cateObj)
    }
     // Just show the latest item.
    const  displayRender = label => label.join('/')
    // 确认添加分类
    const handleAddCate = () => {
        addCateForm.validateFields()
        .then(async ({ cat_name, cat_pid }) => {
            console.log(cat_name, cat_pid)
            let pid = 0
            if(cat_pid?.length) {
                pid = cat_pid[cat_pid.length - 1]
            }
            // cat_pid = !cat_pid.length ? 0 : cat_pid[cat_pid.length - 1]
            const { meta } = await addCateAPI({
                cat_name,
                cat_pid: pid,
                cat_level: pid ? cat_pid.length : 0
            })
            if(meta.status !== 201) return message.error('添加分类失败')
            message.success('添加分类成功')
            setIsAddCateVisible(false)
            loadCateList()
          })
          .catch((e) => {
              console.log(e);
           message.error('请按要求填写信息')
          })
    }
    // 取消添加分类
    const handleCancelAddCate = () => {
        setIsAddCateVisible(false)
    }

    // 编辑分类
    const onEditCate = ({cat_id, cat_name}) => {
        editCateForm.resetFields()
        setCateId(cat_id)
        editCateForm.setFieldsValue({cat_name})
        setIsEditCateVisible(true)
    }
    // 确认编辑分类
    const onConfirmEditCate = () => {
        editCateForm.validateFields()
        .then(async ({cat_name}) => {
            setBtnLoading(true)
            const { meta } = await editCateAPI(cateId, cat_name)
            if(meta.status !== 200) {
                setBtnLoading(false)
                return message.error('编辑分类失败')
            }
            setBtnLoading(false)
            message.success('编辑分类成功')
            setIsEditCateVisible(false)
            loadCateList()
        })
        .catch(() => {
            message.error('请规范填写数据')
        })
    }
    // 取消编辑分类
    const onCancelEditCate = () => {
        setIsEditCateVisible(false)
    }
    // 删除分类
    const onDeleteCate = (id) => {
        confirm({
            title: '该操作将永久删除该分类，是否继续？',
            icon: <ExclamationCircleOutlined />,
            okText: '确认',
            cancelText: '取消',
            confirmLoading: btnLoading,
            async onOk() {
              setBtnLoading(true)
              const { meta } = await delCateAPI(id)
              if(meta.status !== 200) {
                setBtnLoading(false)
                return message.error('删除分类失败')
              }
              setBtnLoading(false)
              message.success('删除分类成功')
              loadCateList()
            }
          })
    }

    // 分页改变
    const paginationChange = (pagenum, pagesize) => {
        setQueryInfo(e => ({...e, pagenum, pagesize}))
    }

    // 表格每一列标题
    const columns = [
        {
          title: '#',
          dataIndex: 'index',
          width: '80px'
        },
        {
          title: '分类名称',
          dataIndex: 'cat_name',
          key:'cat_name'
        },
        {
          title: '是否有效',
          dataIndex: 'cat_deleted',
          key:'cat_deleted',
          render:text => {
              const component = <>
              {
                  text ? <CloseCircleOutlined style={{color: 'FF4D4F'}} /> : <CheckCircleOutlined style={{color: '#87D068'}}/>
              }
              </>
              return component
          }
        },
        {
          title: '排序',
          dataIndex: 'cat_level',
          key:'cat_level',
          render: text => {
              const component = <>
              {
                  text === 0 ? <Tag color="processing">一级</Tag> : text === 1 ? <Tag color="success">二级</Tag> : <Tag color="warning">三级</Tag>
              }
            </>
            return component
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '150px',
          key:'operation',
          render:(_, record) => {
            const component = <>
            <Space>
              <Button onClick={() => onEditCate(record)} icon={<EditOutlined />} type="primary">编辑</Button>
              <Button onClick={() => onDeleteCate(record.cat_id)} icon={<DeleteOutlined />} type="danger">删除</Button>
            </Space>
            </>
            return component
          }
        }
      ]

    return (
        <Card className="cate-container">
            <Button type="primary" onClick={addCate}>添加分类</Button>
            {/* 商品分类 table */}
            <Table
                bordered
                columns={columns}
                dataSource={cateList}
                pagination={false}
                rowKey="cat_id"
                scroll={{y:'600px', x:true}}
                expandable={{
                    expandIconColumnIndex:1
                }}
            />
            {/* 分页 */}
            <Pagination
                total={cateTotal}
                showTotal={total => `总共 ${total} 条`}
                defaultPageSize={queryInfo.pagesize}
                current={queryInfo.pagenum}
                pageSizeOptions={[5,10,20,10]}
                onChange={paginationChange}
                showSizeChanger
            />
            {/* 增加分类模态框 */}
            <Modal cancelText="取消" okText="确认" title="增加分类" visible={isAddCateVisible} onOk={handleAddCate} onCancel={handleCancelAddCate}>
            <Form
                name="addcate"
                form={addCateForm}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
            >
                <Form.Item
                    label="分类名称"
                    name="cat_name"
                    rules={[{required:true, message: '分类名称不能为空'}]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="父级分类"
                    name="cat_pid"
                >
                     <Cascader
                         options={cascaderList}
                         expandTrigger="hover"
                         displayRender={displayRender}
                         changeOnSelect
                         placeholder="请选择"
                         fieldNames={{
                                 label: 'cat_name',
                                 value: 'cat_id'
                             }}
                         onFocus={optionsFocus}
                     />
                </Form.Item>
            </Form>
            </Modal>
            {/* 编辑分类 */}
            <Modal
                cancelText="取消"
                okText="确认"
                title="编辑分类"
                confirmLoading={btnLoading}
                visible={isEditCateVisible}
                onOk={onConfirmEditCate}
                onCancel={onCancelEditCate}
            >
            <Form
                name="editcate"
                form={editCateForm}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
            >
                <Form.Item
                    label="分类名称"
                    name="cat_name"
                    rules={[{required:true, message: '分类名称不能为空'}]}
                >
                    <Input />
                </Form.Item>
            </Form>
            </Modal>
        </Card>
    )
}
